package com.fescoservice.util;

import java.io.UnsupportedEncodingException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * StringUtils.java 字符串处理工具类
 * 
 * @version 1.0
 * @author MIKM 
 * Written Date: 2006-3-31
 * 
 */
public class StringUtil {

	private static final char hex[] = { '0', '1', '2', '3', '4', '5', '6', '7',
			'8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
	
	/** 去掉字符串首尾的空格 判断字符串是否为空，为空直接返回，不为空去掉空格后返回
	 * @param str
	 * @return
	 */
	public static String trim(String str) {
		if (MiscUtil.isNullOrEmpty(str))
			return str;
		return str.trim();
	}

	/** 去掉字符串首尾的空格及全角空格 判断字符串是否为空，为空直接返回，不为空去掉空格后返回
	 * @param str
	 * @return
	 */
	public static String trim2(String str) {
		if (MiscUtil.isNullOrEmpty(str))
			return str;
		return trimFilling(trimFilling(str.trim(), '　', false), '　', true);
	}

	/** 去除字串中的填充字符
	 * @param str 字串
	 * @param filling 填充字符
	 * @param leftJustified true：字串左对齐；false：字串右对齐
	 * @return 去除填充字符后的字串
	 */
	public static String trimFilling(String str, char filling, boolean leftJustified) {
		if (str == null || str.length() == 0)
			return str;
		if (leftJustified) {
			int pos = str.length() - 1;
			for (; pos >= 0; pos--) {
				if (str.charAt(pos) != filling)
					break;
			}
			return str.substring(0, pos + 1);
		}
		int pos = 0;
		for (; pos < str.length(); pos++) {
			if (str.charAt(pos) != filling)
				break;
		}
		return str.substring(pos);
	}

	/** 去除HTML字串中的控制字符及不可视字符
	 * @param str HTML字串
	 * @return 返回的字串
	 */
	public static String escapeHTML(String str) {
		int length = str.length();
		int newLength = length;
		boolean someCharacterEscaped = false;
		for (int i = 0; i < length; i++) {
			char c = str.charAt(i);
			int cint = 0xffff & c;
			if (cint < 32)
				switch (c) {
				case 11:
				default:
					newLength--;
					someCharacterEscaped = true;
					break;

				case '\t':
				case '\n':
				case '\f':
				case '\r':
					break;
				}
			else
				switch (c) {
				case '"':
					newLength += 5;
					someCharacterEscaped = true;
					break;

				case '&':
				case '\'':
					newLength += 4;
					someCharacterEscaped = true;
					break;

				case '<':
				case '>':
					newLength += 3;
					someCharacterEscaped = true;
					break;
				}
		}
		if (!someCharacterEscaped)
			return str;

		StringBuffer sb = new StringBuffer(newLength);
		for (int i = 0; i < length; i++) {
			char c = str.charAt(i);
			int cint = 0xffff & c;
			if (cint < 32)
				switch (c) {
				case '\t':
				case '\n':
				case '\f':
				case '\r':
					sb.append(c);
					break;
				}
			else
				switch (c) {
				case '"':
					sb.append("&quot;");
					break;

				case '\'':
					sb.append("&apos;");
					break;

				case '&':
					sb.append("&amp;");
					break;

				case '<':
					sb.append("&lt;");
					break;

				case '>':
					sb.append("&gt;");
					break;

				default:
					sb.append(c);
					break;
				}
		}
		return sb.toString();
	}

	/** 去除SQL字串中的控制字符
	 * @param str SQL字串
	 * @return 返回的字串
	 */
	public static String escapeSQL(String str) {
		int length = str.length();
		int newLength = length;
		for (int i = 0; i < length;) {
			char c = str.charAt(i);
			switch (c) {
			case 0:
			case '"':
			case '\'':
			case '\\':
				newLength++;
			default:
				i++;
				break;
			}
		}
		if (length == newLength)
			return str;

		StringBuffer sb = new StringBuffer(newLength);
		for (int i = 0; i < length; i++) {
			char c = str.charAt(i);
			switch (c) {
			case '\\':
				sb.append("\\\\");
				break;

			case '"':
				sb.append("\\\"");
				break;

			case '\'':
				sb.append("\\'");
				break;

			case 0:
				sb.append("\\0");
				break;

			default:
				sb.append(c);
				break;
			}
		}
		return sb.toString();
	}

	/** 将一个字符串分解成几个段
	 * @param str 字符串
	 * @param segLen 每段限长
	 * @param segNum 分解段数
	 * @return 分解后的字串组
	 */
	public static String[] split(String str, int segLen, int segNum) {
		String[] result = new String[segNum];
		if (str == null || str.length() == 0)
			return result;

		byte[] strByte;
		try {
			strByte = str.getBytes("GBK");
		} catch (UnsupportedEncodingException ex) {
			strByte = str.getBytes();
		}
		int pos = 0;
		for (int i = 0; i < segNum; i++) {
			int actLen = ((strByte.length - pos) < segLen) ? (strByte.length - pos)
					: segLen;
			byte[] b = new byte[actLen];
			System.arraycopy(strByte, pos, b, 0, actLen);
			result[i] = new String(b);
			pos += actLen;
			if (pos >= strByte.length)
				break;
		}
		return result;
	}

	/** 将一个字符串分解成几个段，每段都能正常转换为IBM935字符集
	 * @param str 字符串
	 * @param segLen 每段限长
	 * @param segNum  分解段数
	 * @return 分解后的字串组
	 */
	public static String[] split4Cp935(String str, int segLen, int segNum) {
		String[] result = new String[segNum];
		byte[] strByte;
		try {
			strByte = str.getBytes("GBK");
		} catch (UnsupportedEncodingException ex) {
			strByte = str.getBytes();
		}
		int strLen = strByte.length;
		byte[] tmpByte = new byte[2 * strLen + segLen];

		int head;
		int flag;
		int count;

		int strCount = 0;
		int segCount = 0;
		int lastStrCount = 0;

		for (flag = 0, head = 0, count = 0; strCount < strLen
				&& segCount < segNum; count++) {
			if ((strByte[strCount] & 0x80) != 0) {
				head = (1 == head) ? 0 : 1;
				if (flag == 0) {
					tmpByte[count] = (byte) ' ';
					flag = 1;
					count++;
				}

				if ((count == ((count / segLen) + 1) * segLen - 2)
						&& (1 == head)) {
					tmpByte[count] = (byte) ' ';
					tmpByte[count + 1] = (byte) ' ';
					result[segCount] = str.substring(lastStrCount, strCount);
					lastStrCount = strCount;
					segCount++;
					tmpByte[count + 2] = (byte) ' ';
					flag = 1;
					count = count + 3;
				} else if (((segLen * ((count + 1) / segLen) - 1) == count)
						&& (1 == head)) {
					tmpByte[count] = (byte) ' ';
					byte[] tmp = new byte[strCount - lastStrCount];
					System.arraycopy(strByte, lastStrCount, tmp, 0, tmp.length);
					result[segCount] = new String(tmp);
					lastStrCount = strCount;
					segCount++;
					tmpByte[count + 1] = (byte) ' ';
					count = count + 2;
					flag = 1;
				} else if (((segLen * (count / segLen)) == count)
						&& (1 == head)) {
					byte[] tmp = new byte[strCount - lastStrCount];
					System.arraycopy(strByte, lastStrCount, tmp, 0, tmp.length);
					result[segCount] = new String(tmp);
					lastStrCount = strCount;
					segCount++;
					tmpByte[count] = (byte) ' ';
					count++;
					flag = 1;
				}
			} else {
				if (1 == flag) {
					tmpByte[count] = (byte) ' ';
					count++;
					flag = 0;
					if (count == (count / segLen) * segLen) {
						byte[] tmp = new byte[strCount - lastStrCount];
						System.arraycopy(strByte, lastStrCount, tmp, 0,
								tmp.length);
						result[segCount] = new String(tmp);
						lastStrCount = strCount;
						segCount++;
					} else {
						if ((segLen * ((count + 1) / segLen) - 1) == count) {
							byte[] tmp = new byte[strCount - lastStrCount + 1];
							System.arraycopy(strByte, lastStrCount, tmp, 0,
									tmp.length);
							result[segCount] = new String(tmp);
							lastStrCount = strCount + 1;
							segCount++;
						}
					}
				} else {
					if ((segLen * ((count + 1) / segLen) - 1) == count) {
						byte[] tmp = new byte[strCount - lastStrCount + 1];
						System.arraycopy(strByte, lastStrCount, tmp, 0,
								tmp.length);
						result[segCount] = new String(tmp);
						lastStrCount = strCount + 1;
						segCount++;
					}
				}

			}
			tmpByte[count] = strByte[strCount];
			strCount++;
			if (strCount >= strLen && segCount < segNum) {
				byte[] tmp = new byte[strCount - lastStrCount];
				System.arraycopy(strByte, lastStrCount, tmp, 0, tmp.length);
				result[segCount] = new String(tmp);
				lastStrCount = strCount;
				segCount++;
			}

			if ((count + 1) % segLen == 0) {
				flag = 0;
			}
		}

		return result;
	}

	/** 取得字符串字节长度,使用缺省字符集
	 * @param str
	 * @return length
	 */
	public static int getByteLength(String str) {
		return str.getBytes().length;
	}

	/** 将带分隔符的字符串转换成List
	 * @param str
	 * @param separator
	 * @return
	 */
	public static List splitString(String str, String separator) {
		return new ArrayList<String>(Arrays.asList(str.split(separator)));
	}

	public static String xml2String(byte[] xml) {
		if (xml == null)
			return null;
		if (xml.length == 0)
			return "";
		try {
			if (xml.length > 20) {
				int max = Math.min(100, xml.length);
				int i = 0;
				while (i < max && xml[i] != '<')
					i++;
				int j = i;
				while (j < max && xml[j] != '>')
					j++;
				if (j - i > 15) {
					String head = new String(xml, i, j - i + 1, "ISO-8859-1");
					i = head.indexOf("encoding=");
					if (i != -1) {
						i += "encoding=".length();
						char q = head.charAt(i);
						j = head.indexOf(q, i + 1);
						if (j != -1) {
							head = head.substring(i + 1, j);
							return new String(xml, head);
						}
					}
				}
			}
		} catch (Throwable t) {
		}
		return new String(xml);
	}

	/** 得到以head开头,tail结尾的子串
	 * @param buffer
	 * @param head
	 * @param tail
	 * @return
	 */
	public static String subString(String buffer, String head, String tail) {
		if (buffer == null || head == null || tail == null)
			return buffer;
		int startNum = buffer.indexOf(head);
		int endNum = buffer.lastIndexOf(tail);

		startNum = startNum >= 0 ? startNum : 0;
		endNum = endNum >= 0 ? endNum + tail.length() : buffer.length();
		return buffer.substring(startNum, endNum);
	}

	/** 转换为十六进制格式（小写）
	 * @param abyte0
	 * @return
	 */
	public static final String bytes2HexStr(byte abyte0[]) {
		StringBuffer stringbuffer = new StringBuffer(abyte0.length * 2);
		for (int i = 0; i < abyte0.length; i++) {
			stringbuffer.append(hex[abyte0[i] >>> 4 & 0xf]);
			stringbuffer.append(hex[abyte0[i] & 0xf]);
		}

		return stringbuffer.toString();
	}

	/** 将用separator分隔的String转化为List，如果str中没有separator则返回的List中只有 str一项
	 * @param str
	 * @param separator
	 * @return
	 */
	public static List str2List(String str, String separator) {
		if (MiscUtil.isNullOrEmpty(str)) {
			return null;
		}
		if (str.trim().length()==0) {
			return null;
		}
		List<String> result = new ArrayList<String>();
		if (str.indexOf(separator) < 0) {
			result.add(str);
		} else {
			String[] strArray = str.split(separator);

			for (int i = 0; i < strArray.length; i++) {
				result.add(strArray[i]);
			}
		}
		return result;
	}

	/** 去除字符串中空白字符
	 * @param str
	 * @return
	 */
	public static String filterSBCCase(String str) {
		char[] ch = str.toCharArray();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < ch.length; i++) {
			if (!Character.isWhitespace(ch[i])) {
				sb.append(String.valueOf(ch[i]));
			}
		}
		return sb.toString();
	}

	/** 字符串是否全数字（无符号、小数点）
	 * @param str
	 * @return
	 */
	public static boolean isDigit(String str) {
		char c;
		for (int i = 0; i < str.length(); i++) {
			c = str.charAt(i);
			if (c < '0' || c > '9')
				return false;
		}
		return true;
	}

	/** 字符串是否全数字或英文字母（无符号、小数点）
	 * @param str
	 * @return
	 */
	public static boolean isAlphaDigit(String str) {
		char c;
		for (int i = 0; i < str.length(); i++) {
			c = str.charAt(i);
			if (c < '0' || c > '9' && c < 'A' || c > 'Z' && c < 'a' || c > 'z')
				return false;
		}
		return true;
	}

	/** 按千位分割格式格式化数字
	 * @param v
	 * @param scale
	 * @return
	 */
	public static String parseStringPattern(Object v, int scale) {
		String temp = "###,###,###,###,###,###,###,##0";
		if (scale > 0)
			temp += ".";
		for (int i = 0; i < scale; i++)
			temp += "0";
		DecimalFormat format = new DecimalFormat(temp);
		return format.format(v).toString();
	}

	/** 将Object转为String[]
	 * @param object
	 * @return
	 */
	public static String[] getStringArray(Object object) {
		if (object instanceof String[])
			return (String[]) object;
		if (object instanceof String) {
			String tmpStrs[] = new String[1];
			tmpStrs[0] = (String) object;
			return tmpStrs;
		}
		return null;
	}

	public static String ADEncoding(String str) {
		if (str == null || str.length() == 0 || isDigit(str)
				&& !str.startsWith("99"))
			return str;
		StringBuffer buf = new StringBuffer("99");
		char c;
		for (int i = 0; i < str.length(); i++) {
			c = str.charAt(i);
			if (c > '\u00ff')
				buf.append("99");
			else if (c > '~')
				buf.append("98");
			else if (c == '\t')
				buf.append("95");
			else if (c == '\r' || c == '\n')
				buf.append("96");
			else if (c < ' ')
				buf.append("97");
			else if (c >= '0' && c <= '9')
				buf.append('0').append(c);
			else if (c >= 'A' && c <= 'Z')
				buf.append((char) ((c - 'A' + 10) / 10 + '0')).append(
						(char) ((c - 'A' + 10) % 10 + '0'));
			else if (c >= 'a' && c <= 'z')
				buf.append((char) ((c - 'a' + 40) / 10 + '0')).append(
						(char) ((c - 'a' + 40) % 10 + '0'));
			else if (c < '0')
				buf.append((char) ((c - ' ' + 66) / 10 + '0')).append(
						(char) ((c - ' ' + 66) % 10 + '0'));
			else if (c < 'A')
				buf.append((char) ((c - ':' + 82) / 10 + '0')).append(
						(char) ((c - ':' + 82) % 10 + '0'));
			else if (c < 'a')
				buf.append((char) ((c - '[' + 89) / 10 + '0')).append(
						(char) ((c - '[' + 89) % 10 + '0'));
			else
				// if (c >= '{')
				buf.append((char) ((c - '{' + 36) / 10 + '0')).append(
						(char) ((c - '{' + 36) % 10 + '0'));
		}
		return buf.toString();
	}

	public static String ADDecoding(String str) {
		if (str == null || str.length() < 4 || !str.startsWith("99")
				|| (str.length() & 1) == 1)
			return str;
		StringBuffer buf = new StringBuffer();
		for (int i = 2; i < str.length(); i += 2) {
			int n = (str.charAt(i) - '0') * 10 + str.charAt(i + 1) - '0';
			if (n < 10)
				buf.append(n);
			else if (n < 36)
				buf.append((char) (n - 10 + 'A'));
			else if (n < 40)
				buf.append((char) (n - 36 + '{'));
			else if (n < 66)
				buf.append((char) (n - 40 + 'a'));
			else if (n < 82)
				buf.append((char) (n - 66 + ' '));
			else if (n < 89)
				buf.append((char) (n - 82 + ':'));
			else if (n < 95)
				buf.append((char) (n - 89 + '['));
			else if (n == 95)
				buf.append('\t');
			else if (n == 96)
				buf.append('\n');
			else if (n == 97)
				buf.append('\u00a9');
			else if (n == 98)
				buf.append('\u00c5');
			else
				// if (n == 99)
				buf.append('\u2592');
		}
		return buf.toString();
	}

	/** 取得类的简单名
	 * @param claz
	 * @return 类的简单名
	 */
	public static String getSimpleName(Class claz) {
		if (claz == null)
			return null;
		return claz.getName().substring(claz.getName().lastIndexOf(".") + 1);
	}

	/** 将一个List转换成,分隔的字符串
	 * @param list
	 * @return
	 */
	public static String stringList2String(List list) {
		StringBuffer sb = new StringBuffer();
		for (int i=0;i<list.size();i++) {
			if (i!=0) {
				sb.append(",");
			}
			sb.append(list.get(i));
		}
		return sb.toString();
	}
	
	/** 将字符串s用sep分隔成字符串数组
	 * @param s
	 * @param sep
	 * @return
	 */
	public static String[] splitFileString(String s, String sep) {
		List<String> list = new ArrayList<String>();
		String temp = s;
		while (temp.indexOf(sep)!=-1) {
			list.add(temp.substring(0, temp.indexOf(sep)));
			temp = temp.substring(temp.indexOf(sep)+1);
		}
		return (String[])list.toArray(new String[list.size()]);
	}
	
	/** 去掉字符串的head部分，如果有的话
	 * @param s
	 * @param head
	 * @return
	 */
	public static String substractHead(String s, String head) {
		if (MiscUtil.isNullOrEmpty(s)) {
			return "";
		}
		if (!s.startsWith(head)) {
			return s;
		}
		return s.substring(head.length(), s.length());
	}
	
	/** 返回一个密码的掩码
	 * @param password
	 * @return
	 */
	public static String getMaskPassword(String password) {
		StringBuffer sb = new StringBuffer();
		for (int i=0;i<password.length();i++) {
			if ((i<2)||(password.length()-i<3)) {
				sb.append(password.charAt(i));
			}else {
				sb.append("*");
			}
		}
		return sb.toString();
	}
	
	/** 将List转化为String数组
	 * @param list
	 * @return
	 */
	public static String[] list2StringArray(List list) {
		String[] tmpStrs = new String[list.size()];
		for (int i=0;i<list.size();i++) {
			tmpStrs[i] = String.valueOf(list.get(i));
		}
		return tmpStrs;
	}
	
	/** 判断用户是否属于admin组
	 * @param userId
	 * @param adminStr
	 * @return
	 */
	public static boolean isUserIdAdmin(String userId, String adminStr) {
		List list = str2List(adminStr,",");
		for (int i=0;i<list.size();i++) {
			String name = (String)list.get(i);
			if (userId.equals(name)) {
				return true;
			}
		}
		return false;
	}

	public static void main(String args[]) {

	}

	
}
